import axios from 'axios'
import { useUserStore } from '@/store'
import router from '@/router'
import { ElMessage } from 'element-plus'

const service = axios.create({
  baseURL: '/api', // 基础地址
  timeout: 10000,
}) // 创建一个新的axios实例
// 成功1 失败2
service.interceptors.request.use(
  (config) => {
    // 注入token
    const store = useUserStore()
    if (store.token) {
      config.headers.Authorization = `Bearer ${store.token}`
    }
    return config
  },
  (error) => {
    // 失败执行promise
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    // axios默认包裹了data
    const { data, message, code } = response.data
    if (code === 0) {
      return data
    } else {
      ElMessage({ type: 'error', message })
      return Promise.reject(new Error(message))
    }
  },
  async (error) => {
    const store = useUserStore()
    if (error.response.status === 401) {
      ElMessage({ type: 'warning', message: 'token超时了' })
      // 说明token超时了
      await store.logout() // 调用action 退出登录
      //  主动跳到登录页
      await router.push('/login') // 跳转到登录页
      return Promise.reject(error)
    }
    // error.message
    ElMessage({ type: 'error', message: error.message })
    return Promise.reject(error)
  }
)
export default service
